package com.jack.algorithm;

/**
 * Created by zhang_j on 2020/6/29
 */
public class binarysearch {

    public static void main(String[] args) {
        int[] nums = {1,2,2,3,4,5,6,7};
        System.out.println(searchBinary(nums, 1));
        System.out.println(searchBinary(nums, 2));
        System.out.println(searchBinary(nums, 2));
        System.out.println(searchBinary(nums, 3));
        System.out.println(searchBinary(nums, 4));
        System.out.println(searchBinary(nums, 5));
        System.out.println(searchBinary(nums, 6));
        System.out.println(searchBinary(nums, 7));
    }

    private static int searchBinary(int[] nums, int target){
        if(nums == null){
            return -1;
        }
        int n = nums.length;
        int left = 0;
        int right = n - 1;
        while(left <= right){
            int mid = (left + right) / 2;
            if(target == nums[mid]){
                return mid;
            }else if(target > nums[mid]){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        return -1;
    }
}
